import {
  getCarList,
  removeFromCar,
  getProductList,
  collectGoods,
  loginWithCode
} from "../../../api.js"
Page({

  /**
   * 页面的初始数据
   */
  data: {
    startX: "",
    total: 0,
    allCheck: false,
    productList: {},
    productPage: 1,
    isCollect: false,
  },

  /**
   * 生命周期函数--监听页面加载
   */
  // 修改人：颜阁
  // 修改时间：2018-11-22
  // 修改内容：添加产品推荐
  onLoad: function (options) {
    this.init()
    var that = this
    getProductList(getApp().globalData.businessId, '', getApp().globalData.Store.token).then(res => {
      if (res.data.code == 666) {
        that.setData({
          productList: res.data.data
        })
      }
    })
  },
  init() {
    let xp = this;

    wx.getSystemInfo({
      success: (res) => {
        xp.setData({
          mainHeight: res.windowHeight - res.windowWidth / 750 * 53,

        })
      }
    })
  },
  onShow: function () {
    this.onlis()
    getApp().startpage(new Date().getTime())
  },
  onHide() {
    getApp().endpage(new Date().getTime())
  },
  onlis() {
    let token = getApp().globalData.Store.token
    var that = this
    getCarList(token).then(res => {
      if (res.data.code === 666) {
        this.setData({
          carList: res.data.data,
          allCheck: false,
          total: 0
        })
        if (res.data.data.length > 0) {
          wx.setTabBarBadge({
            index: 2,
            text: `${res.data.data.length}`
          })
        } else {
          // 去除tabbar 红点
          wx.removeTabBarBadge({
            index: 2,
          })
        }
      } else if (res.data.code == 111111) {
        that.checkUserInfo()
      } else {
        this.setData({
          allCheck: false,
          total: 0
        })
        wx.showToast({
          title: res.data.msg,
          icon: "none"
        })
      }
    })
  },
  /**
   * 移出购物车
   */
  removeProduct(e) {
    let index = e.target.dataset.index
    let token = getApp().globalData.Store.token
    let current = this.data.carList[index]
    if (!current) return
    /**
     * 先将对应的left清除 不然会导致重复删除
     */
    this.setData({
      [`carList[${index}].left`]: 0
    })

    removeFromCar(token, [current.cart_id]).then(res => {
      if (res.data.code === 666) {
        wx.showToast({
          title: res.data.msg,
          icon: "none"
        })
        let carList = this.data.carList
        carList.splice(index, 1)
        let total = this.data.total - current.price
        total = total > 0 ? total : 0;
        // 去除tabbar 红点
        if (this.data.carList.length === 0) {
          wx.removeTabBarBadge({
            index: 2,
          })
        }
        this.setData({
          carList,
          total
        })
      } else {
        wx.showToast({
          title: res.data.msg,
          icon: "none"
        })
      }
    })
  },
  /**
   * 选中商品
   */
  handleProductCheck(e) {
    let index = e.currentTarget.dataset.index
    let current = this.data.carList[index]
    let total = this.data.total
    let key = `carList[${index}]`

    if (current.isPicked) {
      total -= current.price
    } else {
      total += current.price
    }
    /**
     * 浮点数 js 精度问题 转化为二进制计算导致的
     */
    total = parseFloat(total.toFixed(2))

    current.isPicked = !current.isPicked
    this.setData({
      [key]: current,
      total
    })
  },
  // 全选
  handleCheckAll(e) {
    let carList = this.data.carList
    let total = 0

    for (let i = 0, l = carList.length; i < l; i++) {
      if (carList[i].product_state < 5) {
        carList[i].isPicked = this.data.allCheck ? false : true
        total += this.data.allCheck ? 0 : carList[i].price
      }
    }

    this.setData({
      carList,
      total,
      allCheck: !this.data.allCheck
    })
  },
  /**
   * 处理小程序options encode编码 bug
   */
  encodeJson(p) {
    let keyArr = Object.keys(p)
    let map = Object.create(null)
    let k;
    for (let i = 0, l = keyArr.length; i < l; i++) {
      k = keyArr[i]
      map[k] = encodeURIComponent(p[k])
    }
    return map
  },
  // 创建订单
  createOrder() {
    let pickedArr = this.data.carList.reduce((a, b) => {
      if (b.isPicked) {
        a.push(this.encodeJson(b))
      }
      return a
    }, [])
    if (pickedArr.length) {
      wx.navigateTo({
        url: '/pages/money/settlement/settlement?product=' + JSON.stringify(pickedArr) + '&order_enter_type=2'
      })
    } else {
      wx.showToast({
        title: '抱歉，您还没有挑选需要结算的商品',
        icon: "none"
      })
    }
  },
  // 开始滑动
  touchStart(e) {
    this.setData({
      startX: e.touches[0].clientX
    })
  },
  // 滑动中
  touchMove(e) {
    let xp = this
    let left;
    if (e.touches.length === 1) {
      let moveX = e.touches[0].clientX
      let disX = xp.data.startX - moveX
      let delWidth = 70
      if (disX == 0 || disX < 0) {
        left = 0
      } else if (disX > 20) {
        left = delWidth
      }
    }


    let index = e.currentTarget.dataset.index
    let key = `carList[${index}].left`
    if (left !== void 0) {
      this.setData({
        [key]: left
      })
    }
  },
  onReachBottom(e) {
    wx.showLoading({
      title: '正在加载',
    })
    var that = this
    var pages = that.data.productPage
    var last_pages = that.data.productList.last_page
    var lis = that.data.productList.data
    if (pages == last_pages) {
      wx.showToast({
        title: '暂无更多商品',
        icon: "none"
      })
      return
    } else {
      getProductList(getApp().globalData.businessId, {
        page: ++pages
      }, getApp().globalData.Store.token).then(res => {
        for (var i = 0; i < res.data.data.data.length; i++) {
          lis.push(res.data.data.data[i])
        }
        that.setData({
          productPage: pages,
          productList: that.data.productList
        })
        wx.hideLoading()
      })
    }
  },
  /**
   * 修改人：邵群
   * 修改时间：2018-12-01
   * 修改内容：收藏
   * */
  collect(e) {
    let product_id = String(e.currentTarget.dataset.id);
    let token = getApp().globalData.Store.token;
    let index = e.currentTarget.dataset.ind;
    collectGoods({
      product_id,
      token
    }).then(res => {
      if (res.data.code == 666) {

        let isCollect = 'productList.data[' + index + '].user_wishlist'
        this.setData({
          [isCollect]: this.data.productList.data[index].user_wishlist == 1 ? 0 : 1
        })
        if (this.data.productList.data[index].user_wishlist == 0) {
          wx.showToast({
            title: '已取消收藏',
            icon: 'none',
          })
        } else if (this.data.productList.data[index].user_wishlist == 1) {
          wx.showToast({
            title: '已成功收藏',
            icon: 'none',
          })
        }
      }
    })
  },
  // 检查用户信息授权
  checkUserInfo() {
    const xp = this;
    wx.getSetting({
      success: function (res) {
        if (!res.authSetting['scope.userInfo']) {
          xp.setData({
            isAuth: false
          })
          wx.navigateTo({
            url: '/pages/public/shouquan/shouquan',
          })
        } else {
          xp.setData({
            isAuth: true
          })
          wx.getUserInfo({
            success(res) {
              xp.loginWithCode(res.userInfo)
            }
          })
        }
      }
    })
  },
  //登陆
  loginWithCode(userInfo) {
    const xp = this
    wx.login({
      success({
        code
      }) {
        loginWithCode({
          ...userInfo,
          code,
          business_id: getApp().globalData.businessId
        }).then(res => {
          if (res.data.code === 666) {
            getApp().globalData.Store = res.data.data
            xp.onShow()
          }
        })
      }
    })
  },
  productLis(e) {
    var id = e.currentTarget.dataset.id
    var ind = e.currentTarget.dataset.ind + 1
    wx.navigateTo({
      url: '/pages/public/productdetail/productdetail?id=' + id + '&enter_type=3&position=' + ind,
      success: function (res) { },
      fail: function (res) { },
      complete: function (res) { },
    })
  },
  onTabItemTap: function () {
    this.onlis()
  },
  onShareAppMessage(res) {
    return {
      title: "芮享一种轻奢生活的新方式",
      imageUrl: "https://document.growthupup.com/share1217.png?t=" + new Date().getTime()
    }
  },
})